import fs from 'fs';
import path from 'path';
import { fileURLToPath } from 'url';

const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);

/**
 * 路径映射规则接口
 */
export interface PathMappingRule {
  hostPath: string;
  containerPath: string;
  description: string;
  enabled: boolean;
}

/**
 * 路径映射配置接口
 */
export interface PathMappingConfig {
  customMappings: PathMappingRule[];
  defaultMappings: PathMappingRule[];
  settings: {
    enableCustomMappings: boolean;
    enableDefaultMappings: boolean;
    strictMode: boolean;
    logMappings: boolean;
  };
}

/**
 * 路径映射配置服务
 */
export class PathMappingConfigService {
  private static readonly CONFIG_FILE_PATH = path.join(__dirname, '..', 'config', 'pathMapping.json');
  private static config: PathMappingConfig | null = null;

  /**
   * 加载配置文件
   */
  static loadConfig(): PathMappingConfig {
    if (this.config) {
      return this.config;
    }

    try {
      if (fs.existsSync(this.CONFIG_FILE_PATH)) {
        const configData = fs.readFileSync(this.CONFIG_FILE_PATH, 'utf8');
        this.config = JSON.parse(configData);
        console.log('[PathMappingConfig] 配置文件加载成功');
      } else {
        console.log('[PathMappingConfig] 配置文件不存在，使用默认配置');
        this.config = this.getDefaultConfig();
        this.saveConfig(this.config);
      }
    } catch (error) {
      console.error('[PathMappingConfig] 配置文件加载失败:', error);
      this.config = this.getDefaultConfig();
    }

    return this.config;
  }

  /**
   * 保存配置文件
   */
  static saveConfig(config: PathMappingConfig): void {
    try {
      const configDir = path.dirname(this.CONFIG_FILE_PATH);
      if (!fs.existsSync(configDir)) {
        fs.mkdirSync(configDir, { recursive: true });
      }
      
      fs.writeFileSync(this.CONFIG_FILE_PATH, JSON.stringify(config, null, 2), 'utf8');
      this.config = config;
      console.log('[PathMappingConfig] 配置文件保存成功');
    } catch (error) {
      console.error('[PathMappingConfig] 配置文件保存失败:', error);
      throw error;
    }
  }

  /**
   * 获取默认配置
   */
  static getDefaultConfig(): PathMappingConfig {
    return {
      customMappings: [
        {
          hostPath: '/Users/project',
          containerPath: '/projects',
          description: '默认项目目录映射',
          enabled: true
        }
      ],
      defaultMappings: [
        {
          hostPath: '/Users',
          containerPath: '/projects',
          description: 'macOS用户目录',
          enabled: true
        },
        {
          hostPath: '/home',
          containerPath: '/projects',
          description: 'Linux用户目录',
          enabled: true
        },
        {
          hostPath: 'C:\\',
          containerPath: '/projects',
          description: 'Windows C盘',
          enabled: true
        }
      ],
      settings: {
        enableCustomMappings: true,
        enableDefaultMappings: true,
        strictMode: false,
        logMappings: true
      }
    };
  }

  /**
   * 获取所有启用的映射规则
   */
  static getEnabledMappings(): PathMappingRule[] {
    const config = this.loadConfig();
    const mappings: PathMappingRule[] = [];

    if (config.settings.enableCustomMappings) {
      mappings.push(...config.customMappings.filter(rule => rule.enabled));
    }

    if (config.settings.enableDefaultMappings) {
      mappings.push(...config.defaultMappings.filter(rule => rule.enabled));
    }

    return mappings;
  }

  /**
   * 添加自定义映射规则
   */
  static addCustomMapping(rule: Omit<PathMappingRule, 'enabled'>): void {
    const config = this.loadConfig();
    const newRule: PathMappingRule = { ...rule, enabled: true };
    
    // 检查是否已存在相同的映射
    const existingIndex = config.customMappings.findIndex(
      mapping => mapping.hostPath === rule.hostPath
    );
    
    if (existingIndex >= 0) {
      config.customMappings[existingIndex] = newRule;
      console.log(`[PathMappingConfig] 更新映射规则: ${rule.hostPath} -> ${rule.containerPath}`);
    } else {
      config.customMappings.push(newRule);
      console.log(`[PathMappingConfig] 添加映射规则: ${rule.hostPath} -> ${rule.containerPath}`);
    }
    
    this.saveConfig(config);
  }

  /**
   * 删除自定义映射规则
   */
  static removeCustomMapping(hostPath: string): boolean {
    const config = this.loadConfig();
    const initialLength = config.customMappings.length;
    
    config.customMappings = config.customMappings.filter(
      mapping => mapping.hostPath !== hostPath
    );
    
    if (config.customMappings.length < initialLength) {
      this.saveConfig(config);
      console.log(`[PathMappingConfig] 删除映射规则: ${hostPath}`);
      return true;
    }
    
    return false;
  }

  /**
   * 更新设置
   */
  static updateSettings(settings: Partial<PathMappingConfig['settings']>): void {
    const config = this.loadConfig();
    config.settings = { ...config.settings, ...settings };
    this.saveConfig(config);
  }

  /**
   * 获取当前配置
   */
  static getConfig(): PathMappingConfig {
    return this.loadConfig();
  }

  /**
   * 重置配置为默认值
   */
  static resetConfig(): void {
    const defaultConfig = this.getDefaultConfig();
    this.saveConfig(defaultConfig);
    console.log('[PathMappingConfig] 配置已重置为默认值');
  }

  /**
   * 验证映射规则
   */
  static validateMappingRule(rule: PathMappingRule): { valid: boolean; error?: string } {
    if (!rule.hostPath || !rule.containerPath) {
      return { valid: false, error: '主机路径和容器路径不能为空' };
    }

    if (!path.isAbsolute(rule.hostPath)) {
      return { valid: false, error: '主机路径必须是绝对路径' };
    }

    if (!rule.containerPath.startsWith('/')) {
      return { valid: false, error: '容器路径必须是绝对路径' };
    }

    return { valid: true };
  }
}